//
//  MFWSdk.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-7-23.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//


#import "MFWSdk.h"
#import "MFWUserLoginManager.h"
#import "MFWClick.h"

#import "UIDevice+Hardware.h"
#import "MULLoginManager.h"


//for mac
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

static NSString *const SDK_VERSION = @"20131018";


@interface MFWSdkEnvironment(_InnerMethods)
- (void)fillClientConfig:(MFWClientConfig*)config;
@end

@implementation MFWSdk

+ (NSString*)sdkVersion;
{
    return SDK_VERSION;
}

+ (void)appDidLaunched:(NSDictionary*)launchOptions;
{
    [self appDidLaunched:launchOptions withConfiguration:nil];
}

+ (void)appDidLaunched:(NSDictionary *)launchOptions withConfiguration:(MFWClientConfig *)clientConfig
{
    [MULLoginManager startWithXAuthConsumerKey:clientConfig.consumerKey andConsumerSecret:clientConfig.consumerSecret];
    [MULLoginManager setXAuthDefaultToken:clientConfig.defaultToken andSecret:clientConfig.defaultTokenSecret];
    
    [[MFWSdkEnvironment sharedInstance] fillClientConfig:clientConfig];
    [MFWHttpEngine setApiHost:clientConfig.apiHost];
    
    NSString *mfwUserAgent = [MFWSdkEnvironment sharedInstance].mfwUserAgent;
    if (![MFWStringUtils isEmptyString:mfwUserAgent])
    {
        // register user agent to user-defaults, system webview will use this value as its useragent
        // see detail, http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": mfwUserAgent}];
    }

    /// do logic
    
    if (clientConfig.patchingEnabled)
    {
//        [MFWLuaPatcher sharedInstance].checkApiUrl = clientConfig.patchCheckUrl;
//        [MFWLuaPatcher startCheckAndPatch];
    }

//    MFWSdkEnvironment *environment = [MFWSdkEnvironment sharedInstance];
    
//    NSString *umengAppKey = clientConfig.umengKey;
//    NSString *talkingDataAppKey = clientConfig.talkingDataKey;
//    // 开启MFWClick&第三方统计平台（友盟和TalkingData）
//    [MFWClick startWithReportPolicy:MFWClickReportPolicyRealTime
//                        channelCode:environment.channelId
//                        umengAppKey:umengAppKey
//                  talkingDataAppKey:talkingDataAppKey];
    
//    if (umengAppKey.length > 0) {
        // 获取在线配置参数
//        [MobClick updateOnlineConfig];
//        [UMAnalyticsConfig sharedInstance].appKey = umengAppKey;
//        [UMAnalyticsConfig sharedInstance].channelId = clientConfig.channelId;
//        [UMAnalyticsConfig sharedInstance].bCrashReportEnabled = YES;
        
//        [MobClick startWithConfigure:[UMAnalyticsConfig sharedInstance]];
//        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//        [MobClick setAppVersion:version];
//        [MobClick setEncryptEnabled:YES];
//        [MobClick setCrashReportEnabled:YES];
//    }
    
    //    检测新版本（通过umeng接口）
//    [MobClick checkUpdate:NSLocalizedString(@"发现新版本",nil) cancelButtonTitle:NSLocalizedString(@"稍后再说",nil) otherButtonTitles:NSLocalizedString(@"立即更新",nil)];
    
    // 申请推送用的deviceToken
//    if (IOS8_PLUS)
//    {
//        UIUserNotificationSettings *setting =
//        [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound
//                                                      | UIUserNotificationTypeAlert
//                                                      | UIUserNotificationTypeBadge)
//                                          categories:nil];
//        
//        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
//        [[UIApplication sharedApplication] registerForRemoteNotifications];
//    }
//    else
//    {
//        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert
//                                                                               | UIRemoteNotificationTypeBadge
//                                                                               | UIRemoteNotificationTypeSound)];
//    }
   

    
    // 清除图标上的BadgeNumber
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
//    NSString *utrackAppKey = clientConfig.umtrackAppKey;  // 20140122 长老说不再用UMTrack了
//    // 提交友盟渠道统计UMTrack所需信息
//    if(utrackAppKey.length > 0)
//    {
//        NSString * appKey = utrackAppKey;
//        NSString * deviceName = [[[UIDevice currentDevice] name] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        NSString * mac = [self macString];
//        NSString * idfa = [self idfaString];
//        NSString * idfv = [self idfvString];
//        
//        NSString * urlString = [NSString stringWithFormat:@"http://log.umtrack.com/ping/%@/?devicename=%@&mac=%@&idfa=%@&idfv=%@", appKey,deviceName,mac,idfa,idfv];
//        [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:urlString]] delegate:nil];
//    }else{
//#ifdef DEBUG
//        [[[UIAlertView alloc] initWithTitle:@"缺失友盟渠道UMTrack的Key" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
//#endif
//    }
    
    
}

+ (void)forcePatchEnd;
{
//    [MFWLuaPatcher end];
}

+ (void)testReStart;
{
//    [MFWLuaPatcher testReStart];
}

+(void)registerPushDeviceToken:(NSData*)deviceToken
{
    [MFWClick eventDeviceTokenIfChanged:deviceToken];
    
    [[MFWMessageCenter sharedInstance] registerDeviceToken:deviceToken withInfo:nil];
}

+ (void)processRemoteNotificationWithCommand:(NSDictionary *)userInfo fromLaunch:(BOOL)bFromLaunch;
{
    [[MFWMessageCenter sharedInstance] processRemoteNotificationWithCommand:userInfo fromLaunch:bFromLaunch];
}

+ (void)accountLogout;
{
    [[MFWUserLoginManager sharedInstance] logout];
}

+ (BOOL)accountLoginWithAccount:(NSString*)account password:(NSString*)password resultHandler:(UserLoginFinished)handler;
{
    return [[MFWUserLoginManager sharedInstance] loginWithMFWUserName:account password:password finisheHandler:handler];
}

+ (BOOL)loginWith3rdPart:(MFWShareType)thirdPartType startBind:(void(^)())startBindBlock resultHandler:(UserLoginFinished)handler;
{
    return [[MFWUserLoginManager sharedInstance] loginWithThirdParty:thirdPartType startBind:startBindBlock finisheHandler:handler];
}

+ (BOOL)accountRegister:(NSString*)emailAccount password:(NSString*)password nickName:(NSString*)nickName resultHandler:(UserRegisterFinished)handler;
{
    return [[MFWUserLoginManager sharedInstance] registerWithMFWUserName:emailAccount password:password nickName:(NSString*)nickName finisheHandler:handler];
}

#pragma mark UMTrack相关
+ (NSString * )macString{
    
	int 				mib[6];
	size_t 				len;
	char 				*buf;
	unsigned char	 	*ptr;
	struct if_msghdr 	*ifm;
	struct sockaddr_dl 	*sdl;
    
	mib[0] = CTL_NET;
	mib[1] = AF_ROUTE;
	mib[2] = 0;
	mib[3] = AF_LINK;
	mib[4] = NET_RT_IFLIST;
    
	if ((mib[5] = if_nametoindex("en0")) == 0) {
		printf("Error: if_nametoindex error\n");
		return NULL;
	}
    
	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
		printf("Error: sysctl, take 1\n");
		return NULL;
	}
    
	if ((buf = malloc(len)) == NULL) {
		printf("Could not allocate memory. error!\n");
		return NULL;
	}
    
	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
		printf("Error: sysctl, take 2");
		free(buf);
		return NULL;
	}
    
	ifm = (struct if_msghdr *)buf;
	sdl = (struct sockaddr_dl *)(ifm + 1);
	ptr = (unsigned char *)LLADDR(sdl);
	NSString *macString = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                           *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
	free(buf);
    
	return macString;
}

//+ (NSString *)idfaString {
//    
//    NSBundle *adSupportBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/AdSupport.framework"];
//    [adSupportBundle load];
//    
//    if (adSupportBundle == nil) {
//        return @"";
//    }
//    else{
//        
//        Class asIdentifierMClass = NSClassFromString(@"ASIdentifierManager");
//        
//        if(asIdentifierMClass == nil){
//            return @"";
//        }
//        else{
//            
//            //for no arc
//            //ASIdentifierManager *asIM = [[[asIdentifierMClass alloc] init] autorelease];
//            //for arc
//            ASIdentifierManager *asIM = [[asIdentifierMClass alloc] init];
//            
//            if (asIM == nil) {
//                return @"";
//            }
//            else{
//                
//                if(asIM.advertisingTrackingEnabled){
//                    return [asIM.advertisingIdentifier UUIDString];
//                }
//                else{
//                    return [asIM.advertisingIdentifier UUIDString];
//                }
//            }
//        }
//    }
//}

@end
